<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.chouyangfanganone_delete" @click="handleDelete">删 除</el-button>
        <el-button type="success" size="small" plain v-if="userInfo.role_name.includes('admin')" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </template>
    </avue-crud>
    <el-dialog title="一次抽样数据导入" append-to-body :visible.sync="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-before="uploadBefore">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载
            <i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove,importchouyangfanganone } from '@/api/module/chouyangfanganone';
import { mapGetters } from 'vuex';
import { getToken } from '@/util/auth';
export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        labelWidth:100,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '检验类别',
            prop: 'examineLeibie',
            type:"select",
            dicData: [
              {
                label: '正常检验',
                value: '0'
              },
              {
                label: '加严检验',
                value: '1'
              },
              {
                label: '放宽检验',
                value: '2'
              }
            ],
            formatter: row => {
               return row.examineLeibie == 0 ? '正常检验' :row.examineLeibie == 1?'加严检验':'放宽检验';
            },
            rules: [
              {
                required: true,
                message: '请选择检验类别',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '样本量字码',
            prop: 'zima',
            rules: [
              {
                required: true,
                message: '请输入样本量字码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '接收质量限',
            prop: 'aql',
            rules: [
              {
                required: true,
                message: '请输入接收质量限',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '样本量',
            prop: 'yangbenliang',
            rules: [
              {
                required: true,
                message: '请输入样本量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '接收数',
            prop: 'ac',
            rules: [
              {
                required: true,
                message: '请输入接收数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '拒收数',
            prop: 're',
            rules: [
              {
                required: true,
                message: '请输入拒收数',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: [],
      dataText: [],
      excelForm: {},
      excelBox: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach'
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.chouyangfanganone_add, false),
        viewBtn: this.vaildData(this.permission.chouyangfanganone_view, false),
        delBtn: this.vaildData(this.permission.chouyangfanganone_delete, false),
        editBtn: this.vaildData(this.permission.chouyangfanganone_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleChange(file) {
      this.$export.xlsx(file).then(data => {
        let conData = data.results;
        let headerDate = data.header;
        let dataText=[];
        conData.forEach(item => {
          let obj = {
            ac: item[headerDate[5]], //接收数		false
            aql: item[headerDate[2]], //接收质量限		false
            examineLeibie: item[headerDate[0]], //检验类别：0-正常检验，1-加严检验，2-放宽检验		false
            re: item[headerDate[6]], //拒收数		false
            yangbenliang: item[headerDate[4]], //样本量		false
            llyangbenliang: item[headerDate[3]], //理论样本量
            zima: item[headerDate[1]] //样本量字码
          };
          dataText.push(obj);
        });
        console.log(dataText)
        importchouyangfanganone(dataText).then(({data})=>{
          if(data.success){
            this.refreshChange();
          }
        })
      });
    },
    handleTemplate() {
      window.open(`/api/blade-user/export-template?${this.website.tokenHeader}=${getToken()}`);
    },
    uploadBefore(res, done, loading, column) {
      window.console.log(res);
      this.excelBox = false;
      this.handleChange(res);
      done();
    },
    handleImport() {
      this.excelBox = true;
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
